home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13455 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  60 lines

  1. Path: wormer.fn.net!sysadmin@wormer.fn.net
  2. From: demstar@fn.net (Invalid Opcode)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: Sun, 07 Apr 1996 20:10:12 GMT
  6. Organization: Feist Connections
  7. Message-ID: <4k93to$nsf@wormer.fn.net>
  8. References: <31624BC2.70D2@sooner.net> <4k0nlv$hn6@linet06.li.net>
  9. NNTP-Posting-Host: mark313.fn.net
  10. X-Newsreader: Forte Agent .99b.112
  11.  
  12. Eddie Bush (edwbush@sooner.net) wrote:
  13.  
  14. > I am trying to construct a C function that will recursively convert
  15. > a string such as "1234" into it's integer equivelant (1234).
  16. > 2)the function should be called with a character pointer:
  17. >     Such as:   convert("1234");
  18. >   making the prototype look something like:
  19. >     int convert(char *p);
  20.  
  21. Uhhhhhhhhhhhh....
  22.  
  23. #include <stdio.h>
  24.  
  25. unsigned sztou(char *s);
  26.  
  27. int main(void)
  28. {
  29.     char *num = { "16161" };
  30.  
  31.     printf("\n%u", sztou(num));
  32.  
  33.     return (0);
  34. }
  35.  
  36. unsigned sztou(char *s)
  37. {
  38.     static unsigned n = 1;
  39.     unsigned    val;
  40.  
  41.     if (*s)
  42.     {
  43.         val = sztou(s + 1) + (*s - '0') * n;
  44.         n *= 10;
  45.         return (val);
  46.     }
  47.  
  48.     return(0);
  49. }
  50.  
  51. ????
  52.  
  53. That's the unsigned int, no error checking version.  There are tons of
  54. bad things that could happen with this, so it's by no means acceptable
  55. as anything but an answer to a teaching exercise.  I tried to think of
  56. a way to do sztou without using the temporary val variable, but
  57. nothing (that worked) came to mind.  Pffft.  Oh well.  I'm glad I'm
  58. not in an Intro to C class.  :)
  59.  
  60.